package com.aifeng.hassan_food.mine

import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.recyclerview.widget.RecyclerView
import com.aifeng.base.*
import com.aifeng.common_ui.base.gone
import com.aifeng.common_ui.base.visible
import com.aifeng.common_ui.helper.*
import com.aifeng.common_ui.view.FullyLinearLayoutManager
import com.aifeng.hassan_food.R
import com.aifeng.model.CommonData
import com.aifeng.model.OrderData
import com.aifeng.oss.scaleImage
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.subscribeByFinally
import com.aifeng.viewmodel.OrderViewModel
import kotlinx.android.synthetic.main.activity_shop.*
import kotlinx.android.synthetic.main.layout_empty.*
import kotlinx.android.synthetic.main.layout_list.*
import net.idik.lib.slimadapter.SlimAdapter
import org.koin.androidx.viewmodel.ext.android.getViewModel

class ShopActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_shop)
        initTitle(title = "店铺订单", divider = false)

        swipe_refresh.isRefreshing = true
        getData(pageNum)
    }

    override fun getViewModel() = getViewModel<OrderViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        empty_img.apply {
            layoutParams = LinearLayout.LayoutParams(
                dp2px(80f),
                dp2px(80f)
            ).apply {
                setMargins(0, dp2px(30f), 0, 0)
            }
        }

        empty_hint.text = "暂无相关订单信息！"
        swipe_refresh.refresh { getData(1) }
        recycle_list.loadLinear(baseContext, swipe_refresh) {
            if (!isLoadingMore) {
                isLoadingMore = true
                getData(pageNum)
            }
        }

        mAdapter = SlimAdapter.create()
            .register<OrderData>(R.layout.item_shop_list) { data, injector ->

                val index = mList.indexOf(data)
                val isLast = index == mList.size - 1

                injector.text(R.id.item_shop_number, "订单编号：${data.orderno}")
                    .text(
                        R.id.item_shop_status,
                        when (data.state) {
                            "2" -> "待收货"
                            "99" -> "已完成"
                            else -> ""
                        }
                    )
                    .text(R.id.item_shop_price, data.pricetotal.formatDecimal())
                    .text(
                        R.id.item_shop_waiting,
                        (data.paytotal.toNotDouble() - data.pricetotal.toNotDouble()).formatDecimal()
                    )
                    .text(
                        R.id.item_shop_time,
                        "结算时间：${data.settlementdate.getTimeString()}"
                    )
                    .text(
                        R.id.textView01,
                        if (data.settlementdate.isNullOrEmpty()) "待结算金额" else "已结算金额"
                    )
                    .text(
                        R.id.item_shop_sale,
                        "¥ ${data.saletotal.formatDecimal()}"
                    )
                    .text(
                        R.id.item_shop_total,
                        "共${data.goodslist.size}件商品 合计:¥ ${(data.total.toNotDouble() + data.expressfee.toNotDouble()).formatDecimal()}"
                    )
                    .text(
                        R.id.item_shop_name,
                        "姓名：${data.receiver}   电话：${data.phone}"
                    )
                    .visibility(
                        R.id.item_shop_divider,
                        if (isLast) View.VISIBLE else View.GONE
                    )
                    .with<RecyclerView>(R.id.item_shop_list) {
                        it.apply {
                            isNestedScrollingEnabled = false
                            layoutManager = FullyLinearLayoutManager(baseContext)
                            adapter = SlimAdapter.create()
                                .register<CommonData>(R.layout.item_shop_inner_list) { inner, jector ->
                                    jector.text(R.id.item_shop_name, inner.goodsname)
                                        .text(R.id.item_shop_type, "规格：${inner.specs}")
                                        .text(
                                            R.id.item_shop_price,
                                            setHtmlSmall("¥ ${inner.price.formatDecimalWhenHave()}", "¥")
                                        )
                                        .text(R.id.item_shop_num, "x${inner.num}")
                                        .with<ImageView>(R.id.item_shop_img) { view ->
                                            val imgs = inner.goodimg.split(",")
                                            view.loadRoundedImage(url = imgs[0].scaleImage())
                                        }
                                        .visibility(
                                            R.id.item_shop_set,
                                            if (inner.specstype == "package") View.VISIBLE else View.GONE
                                        )
                                }
                                .attachTo(this)
                        }

                        (it.adapter as SlimAdapter).updateData(data.goodslist)
                    }
            }
            .attachTo(recycle_list)
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().shopList(index, getString("userId"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    val item = it.shopCount
                    shop_waiting.text = item.unsettotal.formatDecimal()
                    shop_done.text = item.settotal.formatDecimal()
                    shop_num01.text = item.unsetnum
                    shop_num02.text = item.setnum

                    mList.apply {
                        if (index == 1) {
                            clear()
                            pageNum = index
                        }
                        addItems(it.list)
                        if (count(it.list) > 0) pageNum++
                    }

                    mAdapter.updateData(mList)
                },
                onFinally = {
                    swipe_refresh.isRefreshing = false
                    isLoadingMore = false
                    empty_view.apply { if (mList.isEmpty()) visible() else gone() }
                }
            )
    }

}
